<template>
    <div class="ocrContent">
        <div class="ocrImg">
            <van-uploader
                v-model="fileList"
                :after-read="afterRead"
                :max-count="1"
                :max-size="isOverSize"
                style="position: relative;"
            />
            <!-- reupload // 覆盖上传 -->
        </div>
        <div class="ocrImgBtn">
            <van-button v-if="ocrValue" style="width: 100%;border-radius: 16px;border: none; transition: all 0.3s ease;" :class="{ active: isActive1 }" type="warning" @click="clean">重新开始</van-button>
            <van-button v-else style="width: 100%;background: #15256a;color: #FFF;border-radius: 16px;border: none; transition: all 0.3s ease;"
                :class="{ active: isActive1 }"
                @click="onturn">开始识别</van-button>
        </div>
        <div class="ocrText" v-if="ocrValue">
            <van-field
                v-model="ocrValue"
                rows="5"
                autosize
                label=""
                type="textarea"
                maxlength="1000"
                placeholder="等待内容生成"
                show-word-limit
                clearable
            />
            <van-button style="width: 100%;border-radius: 16px;border: none;background: #bca1f3;transition: all 0.3s ease;" :class="{ active: isActive2 }" @click="copy(ocrValue)">一键复制</van-button>
        </div>
    </div>
</template>
    
<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showFailToast, showConfirmDialog } from 'vant'
import Tesseract from 'tesseract.js'
import useSettingStore from '@/store/modules/setting'
const settings = useSettingStore()


const route = useRoute()
const router = useRouter()

const fileList = ref<any>([

]);

const isActive1 = ref<boolean>(false)
const isActive2 = ref<boolean>(false)
const ocrValue = ref<any>('')

const handleClick = (type: string) => {
    if (type == '1') {
        isActive1.value = !isActive1.value
        setTimeout(() => {
            isActive1.value = !isActive1.value
        }, 100)
    } else if (type == '2') {
        isActive2.value = !isActive2.value
        setTimeout(() => {
            isActive2.value = !isActive2.value
        }, 100)
    }
}

const afterRead = (file: any) => {
    // 此时可以自行将文件上传至服务器
    console.log(file);
};

const isOverSize = (file: any) => {
    console.log(file);
    console.log(file.type);
    if (file.type == 'image/jpeg' || file.type == 'image/png') {
        return false;
    } else {
        showToast('请选择格式为jpg或png类型的图片')
        return true;
    }
    // const maxSize = file.type == 'image/jpeg' ? 500 * 1024 : 1000 * 1024;
    // return file.size >= maxSize;
};

const clean = () => {
    handleClick('1')
    fileList.value = []
    ocrValue.value = ''
}

const onturn = () => {
    console.log(fileList.value[0]);
    handleClick('1')
    if (fileList.value.length < 1) {
        showToast('请选择图片')
        return;
    } else {
        showConfirmDialog({
            title: '',
            confirmButtonColor: '#bca1f3',
            message: '如果图片无文字内容或模糊可能无法识别，确定要开始扫描吗？',
        })
        .then(() => {
            settings.handlerLoadingShow(true)
            // recognize 第一个参数：图像，第二个：语种
            // const url = 'https://tesseract.projectnaptha.com/img/eng_bw.png'
            let url = fileList.value[0]?.content
            console.log('url', url)
            Tesseract.recognize(
                url,
                'chi_sim+eng+jpn+spa',
                {
                    logger: m => console.log(m)
                }
            // { logger: m => console.log(m) }
            ).then((d) => {
                ocrValue.value = d.data.text
                console.log(ocrValue.value)
                settings.handlerLoadingShow(false)
                if (ocrValue.value == '') {
                    showToast('未识别到文字，请重新进行识别或更换图片')
                }
            })
            .catch((err: any) => {
                settings.handlerLoadingShow(false)
                showFailToast(err || '识别失败请稍后再试')
            })
        })
        .catch(() => {
            // on cancel
        });
    }
}

const copy = (mes: string) => {
    handleClick('2')
    var input = document.createElement('input') 
    input.value = mes 
    document.body.appendChild(input) 
    input.select() 
    document.execCommand('copy') 
    document.body.removeChild(input)
    showToast('复制成功')
}


onMounted(() => {

})

</script>


<style lang="scss" scoped>
.ocrContent {
    width: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px;
    .ocrImg {
        display: flex;
        flex-direction: column;
        align-items: center;
        .imgInfo {
            p {
                margin-bottom: 5px;
                color: #666;
            }
        }
    }
    .ocrImgBtn {
        width: 100%;
        margin-top: 15px;
        .active {
            // background-color: blue; /* 改变背景颜色 */
            transform: scale(1.1); /* 放大按钮 */
        }
    }
    .ocrText {
        margin: 20px 0;
        width: 100%;
        height: auto;
        .active {
            // background-color: blue; /* 改变背景颜色 */
            transform: scale(1.1); /* 放大按钮 */
        }
    }
}
</style>